
<template>
  <div class="report-premise">
    <Row>
      <Col span="6" style="border-right: 1px solid #ccc; height: 500px">
        <Steps :current="currentStep" direction="vertical">
          <Step title="" content="填写报备信息"></Step>
          <Step title="" content="选择到访时间"></Step>
        </Steps>
      </Col>
      <Col span="18" style="padding-left: 20px;">
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80" v-if="currentStep === 0">
          <FormItem label="姓名" prop="name">
            <Input v-model="formValidate.name" placeholder=""></Input>
          </FormItem>
          <FormItem label="称谓" prop="gender">
            <RadioGroup v-model="formValidate.gender">
              <Radio :label="GENDER.male">先生</Radio>
              <Radio :label="GENDER.female">女士</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="客户电话" prop="mobile">
            <Input v-model="formValidate.mobile" placeholder=""></Input>
          </FormItem>
          <FormItem label="">
            <div style="text-align: right">
              <span class="color-orange">隐号报备</span>
              <my-switch v-model="formValidate.progressShow" @on-change="toggleShow" />
            </div>
          </FormItem>
          <FormItem label="报备楼盘" prop="premiseNum">
            <Input v-model="formValidate.premiseNum" placeholder="" v-show="false"></Input>
            <Button v-if="!selectedList.length" type="primary" @click="choosePremisesShow">选择楼盘</Button>
            <div v-else>
              <span v-for="item in selectedList">
                {{item.premisesName + '、'}}
              </span>
            </div>
          </FormItem>
          <FormItem label="备注" prop="remark">
            <Input v-model="formValidate.remark" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder=""></Input>
          </FormItem>
        </Form>
        <!--选择到访时间 -->
        <div v-if="currentStep === 1" class="choose-time">
          <div style="border-bottom: 1px solid #ccc; padding-bottom: 20px;">
            <Button type="primary" ghost @click="choosePremisesShow">添加楼盘</Button>
          </div>
          <div>
            <div v-for="item in selectedList" style="border-bottom: 1px solid #ccc; padding: 10px 0;">
              <div class="flex">
                <div class="flex1">
                  <span style="font-size: 20px; font-weight: 600;">{{item.premisesName}}</span>
                  <img class="premise-del" src="../../assets/images/delete.png" @click="deletePremise(item.premisesId)"/>
                </div>
                <p class="flex1" style="color: red;text-align: center; font-size: 14px;">
                  <img src="../../assets/images/warning.png" v-if="item.errorMsg"/>
                  {{item.errorMsg}}
                </p>
              </div>
              <div style="padding: 10px 0;">
                <p class="show-text">最短报备时间: <span class="color-orange">{{item.specialTime | specialTimeCut}}</span></p>
              </div>
              <div class="flex">
                <div class="flex1">
                  <span class="show-text">预计到访时间</span>
                  <DatePicker type="datetime"
                              :disabled="item.ifSelect=== '0'"
                              v-model="item.hopeVisitTime"
                              format="yyyy-MM-dd hh:mm:ss"
                              :options="recommendTimeOptions"
                              placeholder="请选择时间"
                              style="width: 200px"></DatePicker>
                </div>
                <div class="flex1">
                  <span class="show-text">报备推荐人</span>
                  <Select v-model="item.recommender" clearable  style="width:120px" :disabled="item.ifSelect=== '0'">
                    <Option v-for="recommendItem in item.recommendList"
                            :value="recommendItem.recommenderUuid"
                            :key="recommendItem.recommenderUuid">
                      {{ recommendItem.userName }}
                    </Option>
                  </Select>
                </div>
              </div>
            </div>
          </div>

        </div>
        <!--选择到访时间 -->
      </Col>
    </Row>
    <div style="text-align: right">
      <Button type="primary" ghost v-if="currentStep === 1" @click="currentStep =0 ">上一步</Button>
      <Button type="primary" @click="nextClick">{{buttonText[currentStep]}}</Button>
    </div>
    <Modal v-model="choosePremisesVisible"
            title="选择需报备的楼盘"
           width="1000">
      <div>
        <div class="search-container">
          <Form ref="premisesForm" form="premisesForm" inline v-model="premisesForm">
            <FormItem label="省份市区">
            </FormItem>
            <FormItem  prop="provinceId">
              <Select v-model="premisesForm.provinceId" clearable @on-change="provinceChange"  style="width:120px" >
                <Option v-for="item in provinceList" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
            </FormItem>
            <FormItem  prop="cityId">
              <Select v-model="premisesForm.cityId" clearable @on-change="cityChange"  style="width:120px" >
                <Option v-for="item in cityList" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
            </FormItem>
            <FormItem  prop="areaId">
              <Select v-model="premisesForm.areaId" clearable   style="width:120px" >
                <Option v-for="item in areaList" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
            </FormItem>
            <FormItem label=""  prop="name">
              <Input v-model="premisesForm.name" placeholder="请输入楼盘名称"></Input>
            </FormItem>
            <FormItem label="">
              <Button type="primary" @click="searchPremise()">查询</Button>
              <Button  @click="resetForm()">重置</Button>
            </FormItem>
          </Form>
        </div>
        <!--search-container end-->
        <div>
          <div>
            <Table border ref="selection"
                   :columns="columns"
                   :data="premisesData"
                   @on-select-cancel="selectionPremiseCancel"
                   @on-select="selectionPremise"
                   @on-select-all="selectionPremiseAll"
                   @on-select-all-cancel="selectionPremiseAllCancel"
            ></Table>
            <div style="padding: 20px 0">
              <Page :total="premisesTotal" show-total @on-change="pageChange"/>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" style="text-align: right">
        <span>提示:本次最多报备<span style="color: #f98e68 ">20</span>个楼盘，
          当前选择<span style="color: #f98e68; padding: 0 4px">{{selectedList.length}}</span>个</span>
        <Button type="primary" @click="choosePremises">确认选择</Button>
      </div>
    </Modal>
    <Modal v-model="reportSuccessVisible" width="500">
      <p slot="header" class="color-orange" style="font-size: 20px">
        <span>报备成功</span>
      </p>
      <div style="">
        <p>等待审核通过之后，即可带看客户啦</p>
      </div>
      <div slot="footer">
        <Button type="primary" @click="reportSuccessVisible = false">好的</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import  { Switch as MySwitch} from 'iview'
  import moment from 'moment'
  import {Service, Utils, Constant} from '../../js/base'
  import _ from 'lodash'
  const { DATE_FORMAT, GENDER } = Constant
  const REPORT_PREMISE_MAX = 20
  export default {
    name: "ReportPremises",
    components: {
      MySwitch, // 不能直接用Switch名称，详情见官网
    },
    mounted () {
      this.init ()
    },
    data () {
      let checkMobile = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入手机号'));
        } else {
          if (!(/^1[3456789]\d{9}$/.test(value))) {
            callback(new Error('手机号有误'));
          }
          callback();
        }
      }
      let checkPremise = (rule, value, callback) => {
        if (!this.selectedList.length) {
          callback(new Error('请输入楼盘'));
        } else {
          callback();
        }
      }
      return {
        GENDER: GENDER,
        REPORT_PREMISE_MAX: REPORT_PREMISE_MAX,
        currentStep: 0,
        formValidate: {
          name: '',
          mobile: '',
          gender: '0',
          remark: '',
          progressShow: false,
          premiseNum: 1, // 无意义数据
        },
        ruleValidate: {
          name: [
            { required: true, message: '姓名不能为空', trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { validator: checkMobile, trigger: 'blur' }
          ],
          gender: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          remark: [
            { type: 'string', max: 200, message: '请输入200字以内', trigger: 'blur' }
          ],
          premiseNum: [
            { required: true },
            { validator: checkPremise, trigger: 'blur' }
          ]
        },
        buttonText: ['下一步，选择到访时间', '提交报备'],
        choosePremisesVisible: false,
        modal_loading: false,
        chooseTotal: 0, // 选中楼盘数量,
        provinceList: [],
        cityList: [],
        areaList: [],
        premisesForm: {
          areaId: '',  // 区域id (Long)
          cityId: '', //城市id (Long)
          name: "",// 楼盘名称
          pageNo: '1',// 当前页码
          pageSize: '10' , //页面大小
          provinceId: '', //省份id (Long)
        },
        columns:[{
            type: 'selection',
            width: 60,
            align: 'center'
          },{
            title: '楼盘名称',
            key: 'premisesName'
          },{
            title: '所在地区',
            key: 'fullAreaName'
          },{
            title: '最短报备时间',
            key: 'specialTime'
          },{
            title: '已推荐客户数',
            key: 'recommendCount'
          }
        ],
        premisesData:[],
        premisesTotal: 0,
        selectedList: [], // 选中的楼盘
        recommendTimeOptions: { // 选择报备时间配置
          disabledDate (date) {
            return date && date.valueOf() < Date.now() - 86400000;
          }
        },
        reportSuccessVisible: false,// 报备成功提示弹框
      }
    },
    filters: {
      specialTimeCut (val) {
        return  val;
        // let text = "分钟"
        // if(val.includes(text)) {
        //   return val.replace(text,"")
        // } else {
        //   return val
        // }
      }
    },
    methods: {
      init () {
      },
      /**
       * 显示楼盘列表
       */
      choosePremisesShow () {
        this.getProvince();
        this.getPremiseList();
        this.choosePremisesVisible = true;
      },
      /**
       * 切换报备方式
       */
      toggleShow () {
        //this.formValidate.progressShow = !this.formValidate.progressShow
      },
      /**
       * 下一步
       */
      nextClick () {
        if(!this.currentStep) {
          this.$refs['formValidate'].validate((valid) => {
            if (valid) {
              this.currentStep ++
            }
          });
        } else {
          // todo
          let len = this.selectedList.length;
          let currentItem = null, warnMsg = '', currentPremiseName = 0
          let submitFlag = true
          for(let i = 0; i < len; i ++) {
            currentItem = this.selectedList[i]
            currentPremiseName = currentItem.premisesName
            if(!currentItem.hopeVisitTime) {
              submitFlag = false
              warnMsg = '报备时间'
              break;
            }
            // if(!currentItem.recommender) {
            //   warnMsg = '报备推荐人'
            //   submitFlag = false
            //   break;
            // }
          }
          if(!submitFlag) {
            Utils.showWarnMsg(`请填写【${currentPremiseName}】的${warnMsg}`)
            return
          }

          // 提交表单
          this.checkReport().then(rsp => {
            this.selectedList.forEach(item => {
              item.errorMsg = '' // 清空错误信息
            })
            this.saveReport ()
          }).catch(e => {
            // Utils.showWarnMsg("存在不符合报备条件的楼盘，请先处理完毕后再进行提交。")
          })
        }
      },
      /**
       * 校验数据
       */
      checkReport() {
        let _this = this;
        let params = this.getCheckParams ()
        return Service.Premise.checkReportList({params, _this})
          .then(rsp => {
            return rsp
          }).catch( err => {
            let errorMsg = err.resData && err.resData.resultMsg || "校验失败"
            if(err && err.result === '0') {
              let errorList = err.resData.batchReportInfo
              if(errorList) {
                let errorIndex= -1
                errorList.forEach( item => {
                  errorIndex = _this.selectedList.findIndex( i => i.premisesId ===item.premisesId) // 找到错误的那条数据
                  if(errorIndex > -1) {
                    _this.$set(_this.selectedList[errorIndex], 'errorMsg', item.errorMsg)
                    _this.$set(_this.selectedList[errorIndex], 'ifSelect', item.ifSelect)
                  }
                })
                return Promise.reject(err)
              } else {
                Utils.showFailMsg(errorMsg)
                return Promise.reject(err)
              }
            } else {
              Utils.showFailMsg(errorMsg)
              return Promise.reject(err)
            }
        })
      },
      /**
       * 保存报备
       */
      saveReport () {
        let _this = this;
        let params = this.getCheckParams ()
        Service.Premise.saveReportList({params, _this})
          .then(rsp => {
            _this.reportSuccessVisible = true
            _this.reportSuccess()
          }).catch( err => {
            Utils.showFailMsg("报备失败")
        })
      },
      /**
       * 整理报备校验、保存接口参数
       */
      getCheckParams (saveFlag = false) {
        let params ={
          reportType: '1', // ???
          staffId: localStorage.getItem('4_userId'), // 。。。
          ...this.formValidate,
          "reportInfoList": [],
        }
        if(params.progressShow) {// 隐号报备
          params.mobile = params.mobile.slice(0,3) + "****" + params.mobile.slice(7,12)
        }
        let reportInfoItem = {}
        this.selectedList.forEach(item => {
           reportInfoItem = {
             "hopeVisitTime": item.hopeVisitTime && moment(item.hopeVisitTime).format(DATE_FORMAT) || "",
             "premisesId": item.premisesId,
             "recommender": item.recommender || '', // "bbcec88d98c440d9bf3ff12a0c68cc46", //
             "specialTime": item.specialTime, //楼盘最短报备时间
             "premisesName": item.premisesName,
           }
          if(saveFlag) {
            delete params.specialTime
            delete params.premisesName
          }
          params.reportInfoList.push(reportInfoItem)
        })
        delete params.progressShow
        delete params.premiseNum
        return params;
      },
      /**
       * 选择楼盘
       */
      choosePremises() {
        if( this.selectedList.length > REPORT_PREMISE_MAX) {
          Utils.showWarnMsg(`最多只能选择${REPORT_PREMISE_MAX}个楼盘`)
          return
        }
        this.choosePremisesVisible = false;
        this.selectedList.forEach( item => {
          if(!item.recommendList) {
            Service.Recommend.getRecommendList(item.premisesId, this).then(list => {
              item.recommendList = list;
            })
          }
        })
      },
      /**
       * 查询楼盘
       */
      searchPremise () {
        this.getPremiseList ()
      },
      /**
       * 重置楼盘搜索查询条件
       */
      resetForm () {
       // this.$refs['premisesForm'].resetFields();
        this.premisesForm.provinceId = ""
        this.premisesForm.cityId = ""
        this.premisesForm.areaId = ""
        this.premisesForm.name = ""
      },
      /**
       * 获取楼盘列表
       */
      getPremiseList () {
        const _this = this
        let params = this.premisesForm;
        params.companyUuid = Utils.getQueryString('companyUuid')
        // 给 data 项设置特殊 key _checked: true 可以默认选中当前项。
        /// 给 data 项设置特殊 key _disabled: true 可以禁止选择当前项。
        Service.Premise.getPremiseList({params, _this}).then(rsp => {
          if(rsp.rows && rsp.rows.length) {
            let index = -1
            rsp.rows.forEach( item => {
              index = this.selectedList.findIndex(i => {
                return i.premisesId === item.premisesId
              })
              if(index > -1) {
                item._checked = true
              }
            })
          }
          _this.premisesData = rsp.rows;
          _this.premisesTotal = rsp.total;
        })
      },
      /**
       * 获取省份列表
       */
      getProvince() {
        const _this = this
        Service.Common.getProvinceList({_this}).then(list => {
          _this.provinceList = list;
        })
      },
      /**
       * 获取城市列表
       */
      getCity(provinceId = 0) {
        const _this = this
        Service.Common.getCityList({_this, provinceId}).then(list => {
          _this.cityList = list;
        })
      },
      /**
       * 获取区列表
       */
      getArea(cityId = 0) {
        const _this = this
        Service.Common.getAreaList({_this, cityId}).then(list => {
          _this.areaList = list;
        })
      },
      /**
       * 省份切换事件
       */
      provinceChange(val) {
        if(val) {
           this.getCity(val)
        } else {
          this.cityList = []
          this.areaList = []
          this.premisesForm.cityId = ''
          this.premisesForm.areaId = ''
        }
      },
      /**
       * 城市切换事件
       */
      cityChange(val) {
        if(val) {
          this.getArea(val)
        } else {
          this.areaList = []
          this.premisesForm.areaId = ''
        }
      },
      /**
       * 楼盘复选去重
       */
      premiseUniq(selectedList) {
        this.selectedList = _.uniqBy([...this.selectedList, ...selectedList], 'premisesId')
      },
      /**
       * 复选框选择楼盘
       */
      selectionPremise(selectedList) {
        this.premiseUniq(selectedList)
      },
      /**
       * 取消
       */
      selectionPremiseCancel(selectedList, item) {
        let index = -1
        index = this.selectedList.findIndex(i => {
          return i.premisesId === item.premisesId
        })
        if(index > -1) {
          this.selectedList.splice(index, 1)
        }
      },
      /**
       * 楼盘列表全选
       */
      selectionPremiseAll(selectedList) {
        this.selectionPremise(selectedList)
      },
      /**
       * 楼盘列表取消全选
       */
      selectionPremiseAllCancel(selectedList) {        
        let index = -1
        this.premisesData.forEach( item => {
            index = this.selectedList.findIndex(i => {
              return i.premisesId === item.premisesId
            })
            if(index > -1) {
                this.selectedList.splice(index, 1)
            }
        })
        
        this.premiseUniq(selectedList)
      },
      /**
       * 楼盘列表翻页
       */
      pageChange (pageNo = 1) {
        this.premisesForm.pageNo = pageNo
        this.getPremiseList()
      },
      /**
       * 删除楼盘
       */
      deletePremise (premisesId) {
        this.selectedList = this.selectedList.filter(item => item.premisesId !== premisesId)
      },
      /**
       * 报备成功后
       */
      reportSuccess () {
        this.$emit('close')
        this.currentStep = 0
        this.formValidate.name = ''
        this.formValidate.mobile = ''
        this.formValidate.gender = '0'
        this.formValidate.remark = ''
        this.formValidate.progressShow = false
        this.selectedList = []
      },
    },
    watch: { //premiseNum
      selectedList: {
        handler (val) {
          this.formValidate.premiseNum = val && val.length
        },
        deep: true,
        immediate: true
      }
    }
  }
</script>

<style lang="less" scoped>
  @import "../../assets/less/common";
  .color-orange {
    color:#f60;
  }
  .report-premise {
    .choose-time {
      height: 500px;
      overflow-y: scroll;
    }
    .premise-del {
      cursor: pointer;
      position: relative;
      top: -5px;
      left: 10px;
    }
    .show-text {
      font-size: 14px;
      color: #767676;
    }
  }
</style>
